/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Dimensions,
    Image,
    ListView,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';
import GoodsRender from "../../utils/GoodsRender";
import StyleUtils from "../../res/styles/StyleUtils";
import ViewUtils from "../../utils/ViewUtils";
import SearchView from "../../custom/SearchView";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../httpUtils/IparNetwork";
import CommonUtils from "../../common/CommonUtils";
import RegionsIcon from "../../common/RegionsIcon";
import I18n from '../../res/language/i18n'
import IparImageView from "../../custom/IparImageView";

let clickTypes = {search: 'search-type'};

let width = Dimensions.get('window').width;

export default class CategoryTableOneView extends Component {

    //构造函数
    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.regionsIcon = new RegionsIcon();

        let ds = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 != row2,
        });
        this.country = '';
        this.state = {
            visibleSearch: false,
            loading: false,
            advert: [],
            dataSourceRegions: ds,
            dataSourceGoods: ds,
        }
    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('country_iso')
            .then((country) => {
                this.country = country;
                this.onLoadRegionData();
                this.onLoadData();
            });
    }


    /**
     * 获取各位国家的数据
     */
    onLoadRegionData() {
        this.iparNetwork.getRequest(SERVER_TYPE.uiAdminIpar + 'region', '')
            .then((result) => {
                if (result.code === 200) {
                    this.setState({
                        dataSourceRegions: this.state.dataSourceRegions.cloneWithRows(result.data)
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                console.log('CategoryTableOneView--onLoadRegionData--error', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })
    }


    /**
     * 获取信息
     */
    onLoadData(country) {
        this.showLoading(true);


        let _country = country ? '&country=' + country : '';
        this.iparNetwork.getRequest(SERVER_TYPE.uiAdminIpar + 'shopGlobal?',
            'userCountry=' + this.country + _country)
            .then((result) => {
                if (result.code === 200) {
                    let dataBlob = result.data.product;
                    if (dataBlob.length <= 0 && !country) {
                        this.props.isDataNull();
                        return;
                    }
                    this.setState({
                        loading: false,
                        advert: result.data.advert,
                        dataSourceGoods: this.state.dataSourceGoods.cloneWithRows(dataBlob)
                    })
                } else {
                    this.showLoading(false);
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                this.showLoading(false);
                console.log('CategoryTableOneView--componentDidMount---error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })

    }


    /**
     * horizontal ListView
     * @param rowData
     * @returns {*}
     * @private
     */
    _renderTopRow(rowData, rowID) {
        if (rowData.region_id === this.country) return null;

        /**
         临时解决
         */
        let icon = this.regionsIcon.getIcons(rowData.region_id);

        return (
            <TouchableOpacity
                onPress={() => this.onLoadData(rowData.region_id)}
                style={[styles.globalShopIconBox]}>
                <Image
                    resizeMode="cover"
                    style={styles.globalShopIcon}
                    source={icon}
                />
                <Text
                    numberOfLines={1}
                    style={[styles.globalShopText, StyleUtils.smallFont]}>{rowData.region_name}</Text>
            </TouchableOpacity>
        );
    }


    _renderRowGoods(rowData, sectionID, rowID) {
        return (
            <GoodsRender
                navigator={this.props.navigator}
                key={rowID}
                dataSource={rowData}
                countryImage={true}/>
        )
    }

    /**
     * 初始化list view
     * */
    renderListView(dataSource) {
        return (
            <ListView
                renderRow={this._renderRowGoods.bind(this)}
                contentContainerStyle={styles.gridListStyle}
                dataSource={dataSource}/>
        );
    }

    /**
     * 点击事件
     * */
    onClick(type) {
        if (clickTypes.search){
            this.setState({
                visibleSearch: true,
            });
        }
    }


    /**
     * 加载效果
     * */
    showLoading(visible) {
        this.setState({
            loading: visible,
        })
    }

    render() {

        return (
            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.loading}
                    />
                }
            >


                {/**search*/}
                <View style={[StyleUtils.justifySpace, styles.searchBox, StyleUtils.marginTop]}>
                    <Image
                        style={[StyleUtils.tabIconSize, {tintColor: '#898b8d'}]}
                        source={require('../../res/images/ic_search.png')}/>
                    <TouchableOpacity
                        onPress={() => this.onClick(clickTypes.search)}
                        style={StyleUtils.flex}>
                        <Text style={[StyleUtils.text, StyleUtils.smallFont]}>{I18n.t('default.search')}</Text>
                    </TouchableOpacity>
                    {/*<TouchableOpacity*/}
                    {/*style={[StyleUtils.center, styles.filterTextBox]}>*/}
                    {/*<Text style={styles.filterText}>FILTER</Text>*/}
                    {/*</TouchableOpacity>*/}
                </View>
                <SearchView
                    {...this.props}
                    updateState={(visible) => {
                        this.setState({visibleSearch: visible})
                    }}
                    visible={this.state.visibleSearch}/>


                {/**广告*/}
                {this.state.advert.length > 0 && <View style={{padding: 16}}>

                    <IparImageView
                        errorImage={require('../../res/images/ic_image_fail.png')}
                        resizeMode={'cover'}
                        width={'100%'}
                        height={width / 1.7}
                        url={this.state.advert[0].adver_img}/>
                </View>}

                <Text style={[StyleUtils.title, StyleUtils.smallFont, {
                    textAlign: null,
                    padding: 16
                }]}>{I18n.t('default.selectConShopFrom')}</Text>

                {/**global shop top select country*/}
                <ListView
                    dataSource={this.state.dataSourceRegions}
                    renderRow={(rowData, sectionID, rowID) => this._renderTopRow(rowData, rowID)}
                    horizontal={true}
                    showsHorizontalScrollIndicator={false}
                    pagingEnabled={true}/>


                {/**globals shop*/}
                {this.renderListView(this.state.dataSourceGoods)}
                <View style={{margin: 16}}>
                    {ViewUtils.getButton(I18n.t('default.showAll'), () => this.onLoadData())}
                </View>


            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({

    globalShopIcon: {
        width: 50,
        height: 30,
        resizeMode: 'cover',
    },
    globalShopIconBox: {
        margin: 6,
        width: 50,
        marginLeft: 16,
    },
    globalShopText: {
        color: '#333',
        paddingTop: 8,
        fontSize: 14,
    },
    filterText: {
        textAlign: 'center',
        fontSize: 18,
        color: '#333333',
    },
    filterTextBox: {
        height: '100%',
        borderLeftWidth: 1,
        paddingLeft: 8,
        borderColor: '#dddddd'
    },
    searchBox: {
        height: 46,
        borderWidth: 1,
        borderColor: '#dddddd',
        paddingRight: 8,
        paddingLeft: 8,
        margin: 16,
        marginBottom: 0,
    },
    gridListStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
    headersImage: {
        height: (width / 2) + 60,
        width: '100%',
        resizeMode: 'cover',
        marginTop: 12,
    },

});
